import LogicFlow from "@logicflow/core";
import "@logicflow/core/dist/index.css";
import { ref, shallowRef, onMounted, onUnmounted } from "vue";
// LogicFlow 实例
const lf = shallowRef<LogicFlow | null>(null);
const lfContainer = ref<HTMLElement | null>(null);

export function useLifecycleHooks() {
  // 初始化 LogicFlow
  function useOnMountedHooks() {
    onMounted(() => {
      if (!lfContainer.value) return;

      lf.value = new LogicFlow({
        container: lfContainer.value,
        grid: {
          size: 20,
          visible: true,
          type: "dot",
          config: {
            color: "rgba(102, 126, 234, 0.2)",
          },
        },
        background: {
          color: "rgba(30, 30, 46, 0.5)",
        },
        keyboard: {
          enabled: true, // 启用键盘快捷键
        },
        edgeType: "bezier", // 默认边类型为贝塞尔曲线
        isSilentMode: false, // 非静默模式，允许删除等操作
        stopScrollGraph: true, // 禁止鼠标滚动移动画布（改用滚轮缩放）
        stopZoomGraph: false, // 允许缩放画布
        style: {
          rect: {
            rx: 8,
            ry: 8,
          },
        },
      });
    });
  }
  // 组件卸载时移除事件监听
  function useOnUnmountedHooks() {
    onUnmounted(() => {
      document.removeEventListener("keydown", handleKeyDown);
    });
  }

  // 添加键盘删除功能
  const handleKeyDown = (e: KeyboardEvent) => {
    if (!lf.value) return;

    // 检查是否按下 Delete 或 Backspace 键
    if (e.key === "Delete" || e.key === "Backspace") {
      // 获取当前选中的元素
      const selectElements = lf.value.getSelectElements();

      if (
        selectElements &&
        selectElements.nodes &&
        selectElements.nodes.length > 0
      ) {
        // 删除选中的节点
        selectElements.nodes.forEach((node: any) => {
          // 先获取与该节点相关的所有边
          const graphData = lf.value!.getGraphData() as any;
          const relatedEdges = graphData.edges.filter(
            (edge: any) =>
              edge.sourceNodeId === node.id || edge.targetNodeId === node.id
          );

          // 删除相关的边
          relatedEdges.forEach((edge: any) => {
            lf.value!.deleteEdge(edge.id);
          });

          // 删除节点
          lf.value!.deleteNode(node.id);
        });

        // 阻止默认行为（防止浏览器后退）
        e.preventDefault();
      } else if (
        selectElements &&
        selectElements.edges &&
        selectElements.edges.length > 0
      ) {
        // 删除选中的边
        selectElements.edges.forEach((edge: any) => {
          lf.value!.deleteEdge(edge.id);
        });

        // 阻止默认行为
        e.preventDefault();
      }
    }
  };

  // 添加键盘事件监听
  document.addEventListener("keydown", handleKeyDown);
  return {
    useOnMountedHooks,
    useOnUnmountedHooks,
    lf,
    lfContainer,
  };
}
